#include "ai_replay.h"



void replay::get_buy_commands( const game_state* gs )
{
	commands.clear();
	cout << "AI BEGIN" << endl;
	if ( all_commands.empty() )
	{
		commands.push_back( "END" );
		cout << "No commands to load, \"NXT\" added!" << endl;
	}
	else
	{
		while ( !all_commands.front()->empty() )
		{
			commands.push_back( all_commands.front()->front() );
			cout << "Loaded command: \"" << all_commands.front()->front() << "\"" << endl;
			all_commands.front()->pop_front();
		}
		delete all_commands.front();
		all_commands.pop();
	}

	cout << "AI END" << endl;
};



void replay::get_commands( const game_state* gs )
{
	commands.clear();
	cout << "AI BEGIN" << endl;
	if ( all_commands.empty() )
	{
		commands.push_back( "NXT" );
		cout << "No commands to load, \"NXT\" added!" << endl;
	}
	else
	{
		while ( !all_commands.front()->empty() )
		{
			commands.push_back( all_commands.front()->front() );
			cout << "Loaded command: \"" << all_commands.front()->front() << "\"" << endl;
			all_commands.front()->pop_front();
		}
		delete all_commands.front();
		all_commands.pop();
	}

	cout << "AI END" << endl;
};



bool replay::init( player* p, const string& s )
{
	owner = p;
	connect( this, SIGNAL( send_command( player*, const string& ) ), game::get_instance(), SLOT( command_received( player*, const string& ) ) );
	if ( parse_commands_line( s ) )
		return true;
	else
		return false;
};



bool replay::parse_commands_line( const string& cl )
{
	list< string >* command_list = new list< string >;
	bool end = false;
	string command;
	istringstream sstr( cl );
	for ( ; ; )
	{
		getline( sstr, command, '#' );
		if ( sstr.fail() )
		{
			return ( end );
		}
		end = false;
		command_list->push_back( command );
		if ( ( command == "NXT" ) || ( command == "END" ) )
		{
			all_commands.push( command_list );
			command_list = new list< string >;
			end = true;
		}
	}
};